#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import logging
import traceback

import requests
import json
import sys
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry

zabbix_api_path = '/api_jsonrpc.php'
from loguru import logger

logger.add("/var/log/Task/Tasks.log", rotation="00:00", backtrace=True, diagnose=True, level="DEBUG")


# -------zabbix 登陆认证，获取token----
def zabbix_get_token(user, passwd, serverurl, verify=None):
    try:
        url = serverurl + zabbix_api_path
        post_data = {
            "jsonrpc": "2.0",
            "method": "user.login",
            "params": {
                "user": user,
                "password": passwd
            },
            "id": 1
        }
        post_header = {'Content-Type': 'application/json'}

        ret = requests.post(url, data=json.dumps(post_data), headers=post_header, verify=verify)
        zabbix_ret = json.loads(ret.text)
        if 'error' in zabbix_ret:
            error = zabbix_ret.get('error')
            logger.info('error:' + error['message'] + ' ' + error['data'])
        elif 'result' in zabbix_ret:
            token = zabbix_ret.get('result')
        return token
    except Exception as e:
        # logger.error(f"zabbix获取token报错：{traceback.format_exc()}")
        logger.info(traceback.format_exc())
        logger.exception(traceback.format_exc())


# ------zabbix获取问题信息---------
def zabbix_get_problem(token, serverip, tag, value, operator):
    url = serverip + zabbix_api_path
    get_data = params = {
        "jsonrpc": "2.0",
        "method": "problem.get",
        "params": {
            "groupids": "25",
            "tags": [{
                "tag": tag,
                "value": value,
                "operator": operator
            }],
        },
        "auth": token,
        "id": 1
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    try:
        zabbix_ret = json.loads(ret.text)
        data = zabbix_ret.get('result')
        return data
    except Exception as e:
        logger.exception(traceback.format_exc())
        return e


# -------zabbix获取模版组信息--exsearch:0/1-------
def zabbix_get_templategroup(token, serverip, templates_name, verify=None):
    try:
        url = serverip + zabbix_api_path
        get_data = {
            "jsonrpc": "2.0",
            "method": "templategroup.get",
            "params": {
                "output": "extend",
                "filter": {
                    "name": [templates_name]
                }
            },
            "id": 11,
            "auth": token
        }
        post_header = {'Content-Type': 'application/json'}
        ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
        zabbix_ret = json.loads(ret.text)
        group_list = zabbix_ret.get('result')

        return group_list
    except Exception as e:
        # logger.error(f"zabbix获取组信息失败：{traceback.format_exc()}")
        logger.info(traceback.format_exc())
        resp_data = {
            "status": "Error",
            "message": f"zabbix获取模版组信息失败, 模板:{templates_name}",
            "detail": traceback.format_exc()
        }
        logger.exception(traceback.format_exc())
        return resp_data


# -------zabbix获取组信息--exsearch:0/1-------
def zabbix_get_group(token, serverip, search_type, search_name, exsearch, verify=None):
    try:
        url = serverip + zabbix_api_path
        get_data = {
            "jsonrpc": "2.0",
            "method": "hostgroup.get",
            "params": {
                "output": [
                    "groupid",
                    "name"],
                "search": {
                    search_type: search_name
                },
                "excludeSearch": exsearch,
                # "searchWildcardsEnabled": "true"
                "searchWildcardsEnabled": True
            },
            "id": 11,
            "auth": token
        }
        post_header = {'Content-Type': 'application/json'}
        ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
        zabbix_ret = json.loads(ret.text)
        group_list = zabbix_ret.get('result')
        if zabbix_ret.get("error"):
            resp_data = {
                "status": "Error",
                "message": "zabbix 获取组信息失败",
                "detail": zabbix_ret.get("error")
            }
            return resp_data
        return group_list
    except Exception as e:
        # logger.error(f"zabbix获取组信息失败：{traceback.format_exc()}")
        logger.info(traceback.format_exc())
        resp_data = {
            "status": "Error",
            "message": "zabbix 获取组信息失败",
            "detail": traceback.format_exc(),
        }
        logger.exception(traceback.format_exc())
        return resp_data


# -------zabbix获取主机信息-id:12--------
def zabbix_get_hosts(token, serverip, filter_type, filter_host, verify=None):
    url = serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "host.get",
        "params": {
            "output": [
                "hostid",
                "name",
                "interfaces"
                "status"
            ],
            "filter": {
                filter_type: [
                    filter_host
                ]
            }
        },
        "id": 12,
        "auth": token
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    try:
        zabbix_ret = json.loads(ret.text)
    except:
        logger.info(ret)
        logger.info(ret.text)
    if 'error' in zabbix_ret:
        error = zabbix_ret.get('error')
        logger.info('error:' + error['message'] + ' ' + error['data'])
    elif 'result' in zabbix_ret:
        # print('查询'+filter_host+'结果:'+str(zabbix_ret['result']))
        pass
    return zabbix_ret


# -------zabbix获取主机信息2-id:13--------
def zabbix_get2_hosts(token, serverip, filter_type, filter_host, verify=None):
    url = serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "host.get",
        "params": {
            "output": [
                "hostid",
                "name",
                "status"
            ],
            filter_type: filter_host
        },
        "id": 13,
        "auth": token
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)

    if 'error' in zabbix_ret:
        error = zabbix_ret.get('error')
        logger.info('error:' + error['message'] + ' ' + error['data'])
        sys.exit()
    else:
        hosts_list = zabbix_ret.get('result')
    return hosts_list


# -------zabbix获取模板信息-id:14--------
def zabbix_get_templates(token, serverip, filter_type, filter_host, verify=None):
    url = serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "template.get",
        "params": {
            "output": [
                "hostid",
                "name",
                "status"],
            "search": {
                filter_type: [
                    filter_host
                ]
            },
            "excludeSearch": '0',
            "searchWildcardsEnabled": "true"
        },
        "id": 14,
        "auth": token
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    hosts_list = zabbix_ret.get('result')
    return hosts_list


# -------zabbix获取接口-id:15--------
def zabbix_get_hostinterface(token, serverip, hostids, verify=None):
    url = serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "hostinterface.get",
        "params": {
            "output": [
                "hostid",
                "interfaceid",
                "ip"],
            "hostids": hostids

        },
        "id": 15,
        "auth": token
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    if 'error' in zabbix_ret:
        error = zabbix_ret.get('error')
        logger.info('error:' + error['message'] + ' ' + error['data'])
    elif 'result' in zabbix_ret:
        # print('查询'+hostids+'结果:'+str(zabbix_ret['result']))
        pass

    return zabbix_ret


# -------zabbix获取自定义宏信息-id:16--------
def zabbix_get_macros(token, serverip, filter_type, filter_host, verify=None):
    url = serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "usermacro.get",
        "params": {
            "output": "extend",
            filter_type: filter_host
        },
        "id": 16,
        "auth": token
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    if 'error' in zabbix_ret:
        error = zabbix_ret.get('error')
        logger.info('error:' + error['message'] + ' ' + error['data'])
    elif 'result' in zabbix_ret:
        # print('查询'+str(filter_host)+'结果:'+str(zabbix_ret['result']))
        pass
    return zabbix_ret


# -------zabbix获取告警信息-id:17--------
def zabbix_get_alerts(token, serverip, filter_type, filter_host, verify=None):
    url = serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "alert.get",
        "params": {
            "output": "extend",
            filter_type: filter_host
        },
        "id": 17,
        "auth": token
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    if 'error' in zabbix_ret:
        error = zabbix_ret.get('error')
        logger.info('error:' + error['message'] + ' ' + error['data'])
    elif 'result' in zabbix_ret:
        # print('查询' + str(filter_host) + '结果:' + str(zabbix_ret['result']))
        pass
    return zabbix_ret['result']


# -------zabbix获取链接到模板的主机-id:18--------
def zabbix_get_template_info(token, serverip, filter_type, filter_host, verify=None):
    # filter_type：https://www.zabbix.com/documentation/3.4/zh/manual/api/reference/template/get
    # 常用值：selectHosts, selectTemplates,
    url = serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "template.get",
        "params": {
            "output": [
                "hostid",
                "name",
                "status"],
            "selectHosts": [
                "hostid",
            ],
            filter_type: filter_host
        },
        "id": 18,
        "auth": token
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    if 'error' in zabbix_ret:
        error = zabbix_ret.get('error')
        logger.info('error:' + error['message'] + ' ' + error['data'])
    elif 'result' in zabbix_ret:
        # print('查询' + str(filter_host) + '结果:' + str(zabbix_ret['result']))
        pass
    return zabbix_ret['result']


# -------zabbix获取历史信息---------
def zabbix_get_history(token, serverip, itemids, time_from, time_till, limit, verify=None):
    url = serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "history.get",
        "params": {
            "output": "extend",
            "history": 3,
            "itemids": itemids,
            "sortfield": "clock",
            "sortorder": "DESC",
            "limit": limit,
        },
        "id": 11,
        "auth": token
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)

    return zabbix_ret


# --------zabbix 获取用户组信息--------
def zabbix_get_usergroup(token, serverip, search_type, search_name, exsearch, verify=None):
    url = serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "usergroup.get",
        "params": {
            "output": "extend",
            "search": {
                search_type: search_name
            },
            "selectRights": [
                "permission",
                "id"
            ],
            "excludeSearch": exsearch,
            "searchWildcardsEnabled": "true"
        },
        "id": 11,
        "auth": token
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    logger.info(zabbix_ret)
    group_list = zabbix_ret.get('result')

    return group_list


# -------zabbix获取用户组信息--exsearch:0/1-------
def zabbix_search_info(token, serverip, option, search_type, search_name, exsearch, verify=None):
    url = serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": option + ".get",
        "params": {
            "search": {
                search_type: search_name
            },
            "excludeSearch": exsearch,
            "searchWildcardsEnabled": "true"
        },
        "id": 18,
        "auth": token
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    group_list = zabbix_ret.get('result')

    return group_list


# ---------zabbix创建简单主机-20------------
def zabbix_create_simple_host(token, serverip, hostip, hostname, descname, group_id, templateid, port_type, status,
                              verify=None):
    if port_type == 1:
        ports = "10050"
    elif port_type == 2:
        ports = "161"
    else:
        logger.info("port_type error:端口类型未识别:" + str(port_type))
        return 'error:port_type error'
    # 判断模板类型
    if isinstance(templateid, list):
        template_value = templateid
    else:
        logger.info(type(templateid))
        template_value = [
            {
                "templateid": templateid
            }
        ]
    url = serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "host.create",
        "params": {
            "host": hostname,
            "name": descname,
            "interfaces": [
                {
                    "type": port_type,
                    "main": 1,
                    "useip": 1,
                    "ip": hostip,
                    "dns": "",
                    "port": ports
                }
            ],
            "groups": [
                {
                    "groupid": group_id
                }
            ],
            "templates": template_value,
            "status": status
        },
        "auth": token,
        "id": 21
    }
    post_header = {'Content-Type': 'application/json'}
    logger.info(json.dumps(get_data))
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    if 'error' in zabbix_ret:
        error = zabbix_ret.get('error')
        logger.info('error:' + error['message'] + ' ' + error['data'])
    elif 'result' in zabbix_ret:
        logger.info('新建' + hostname + '结果:' + str(zabbix_ret['result']))

    return zabbix_ret


# -------------获取主机绑定的模板id  56---------------
def zabbix_get_host_templatesid(serverip, hostid, token, verify=None):
    url = serverip + zabbix_api_path
    get_data = {
                   "jsonrpc": "2.0",
                   "method": "host.get",
                   "params": {
                       "output": ["hostid"],
                       "selectParentTemplates": [
                           "templateid",
                           "name"
                       ],
                       "hostids": hostid
                   },
                   "id": 56,
                   "auth": token
               },
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    template_id = zabbix_ret[0].get('result')
    logger.info(f"获取要清楚的模板id:{template_id}")
    return template_id


# ------- 清除模板: id 55
def zabbix_templates_clear(token, serverip, hostid, name, templateid, verify=None):
    url = serverip + zabbix_api_path
    if isinstance(templateid, list):
        template_value = templateid
    else:
        print(type(templateid))
        template_value = [
            {
                "templateid": templateid
            }
        ]
    get_data = {
        "jsonrpc": "2.0",
        "method": "host.update",
        "params": {
            "hostid": hostid,
            "templates_clear": template_value
        },
        "auth": token,
        "id": 55
    }
    post_header = {'Content-Type': 'application/json'}
    print(json.dumps(get_data))
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    if 'error' in zabbix_ret:
        error = zabbix_ret.get('error')
        logger.error('error:' + error['message'] + ' ' + error['data'])
    elif 'result' in zabbix_ret:
        logger.info('host' + name + '，模板清除成功')
    return zabbix_ret


# ---------zabbix创建主机-21------------
def zabbix_create_host(token, serverip, hostip, hostname, group_id, templateid, port_type, macros, inventory, tags,
                       status, proxy_hostid, verify=None):
    try:
        if port_type == 1:
            ports = "10050"
        elif port_type == 2:
            ports = "161"
            details = {
                "version": "2",
                "community": "{$SNMP_COMMUNITY}"

            }
        else:
            logger.info("port_type error:端口类型未识别:" + str(port_type))
            return 'error:port_type error'
        # 判断group_id类型，string or list
        group_list = []
        if isinstance(group_id, list):
            for gid in group_id:
                group_list.append({"groupid": gid})
        else:
            group_list.append({"groupid": group_id})
        # 判断模板类型
        if isinstance(templateid, list):
            template_value = templateid
        else:
            logger.info(type(templateid))
            template_value = [
                {
                    "templateid": templateid
                }
            ]
        url = serverip + zabbix_api_path
        get_data = {
            "jsonrpc": "2.0",
            "method": "host.create",
            "params": {
                "host": hostname,
                "interfaces": [
                    {
                        "type": port_type,
                        "main": 1,
                        "useip": 1,
                        "ip": hostip,
                        "dns": "",
                        "port": ports,
                    }
                ],
                "groups": group_list,
                "templates": template_value,
                "macros": macros,
                "inventory_mode": 1,
                "inventory": inventory,
                "tags": tags,
                "status": status,
                "proxy_hostid": proxy_hostid
            },
            "auth": token,
            "id": 21
        }
        if port_type == 2:
            get_data['params']['interfaces'][0]['details'] = details
        post_header = {'Content-Type': 'application/json'}
        logger.info(json.dumps(get_data))
        ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
        zabbix_ret = json.loads(ret.text)
        logger.info(json.dumps(zabbix_ret))
        if 'error' in zabbix_ret:
            error = zabbix_ret.get('error')
            resp_data = {
                "status": "Error",
                "message": error,
                "detail": "zabbix创建主机-21失败",
                "hostname": hostname
            }
            return resp_data
        # elif 'result' in zabbix_ret:
        else:
            logger.info('新建' + hostname + '结果:' + str(zabbix_ret['result']))
            resp_data = {
                "status": "Create",
                "message": '新建' + hostname + '结果:' + str(zabbix_ret['result']),
                "hostname": hostname
            }
            return resp_data
    except Exception as e:
        resp_data = {
            "status": "Error",
            "message": "创建失败",
            "detail": traceback.format_exc(),
            "hostname": hostname
        }
        logger.exception(traceback.format_exc())
        return resp_data


# ---------zabbix创建主机(用于线路监控)-29------------
def zabbix_create_line(token, serverip, hostip, hostname, name, groups, templateid, port_type, macros, inventory, tags,
                       status, proxy_hostid, verify=None):
    try:
        if port_type == "1":
            ports = "10050"
        elif port_type == "2":
            ports = "161"
        else:
            logger.info("port_type error:端口类型未识别")
        # 判断模板类型
        if isinstance(templateid, list):
            template_value = templateid
        else:
            logger.info(type(templateid))
            template_value = [
                {
                    "templateid": templateid
                }
            ]
        url = serverip + zabbix_api_path
        get_data = {
            "jsonrpc": "2.0",
            "method": "host.create",
            "params": {
                "host": hostname,
                "name": name,
                "interfaces": [
                    {
                        "type": port_type,
                        "main": 1,
                        "useip": 1,
                        "ip": hostip,
                        "dns": "",
                        "port": ports
                    }
                ],
                "groups": groups,
                "templates": template_value,
                "macros": macros,
                "inventory_mode": 1,
                "inventory": inventory,
                "tags": tags,
                "status": status,
                "proxy_hostid": proxy_hostid
            },
            "auth": token,
            "id": 29
        }
        logger.info(get_data)
        post_header = {'Content-Type': 'application/json'}
        ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
        zabbix_ret = json.loads(ret.text)
        if 'error' in zabbix_ret:
            error = zabbix_ret.get('error')
            logger.info(json.dumps(zabbix_ret))
            logger.info('error:' + error['message'] + ' ' + error['data'])
            resp_data = {
                "status": "Error",
                "message": "zabbix 创建主机(线路监控)失败",
                "detail": zabbix_ret.get('error'),
                "hostname": hostname
            }
            # return resp_data
        # elif 'result' in zabbix_ret:
        else:
            logger.info('Line' + name + '创建成功!')
            resp_data = {
                "status": "Create",
                "message": "zabbix 创建主机(线路监控)成功",
                "hostname": hostname,
                "zabbix_ret": zabbix_ret
            }
        return resp_data
    except Exception as e:
        resp_data = {
            "status": "Error",
            "message": "zabbix 创建主机(线路监控)失败",
            "detail": traceback.format_exc(),
            "hostname": hostname
        }
        logger.exception(traceback.format_exc())
        return resp_data


# ---------zabbix创建主机组-22--------------------
def zabbix_create_group(token, serverip, group_name, verify=None):
    try:
        url = serverip + zabbix_api_path
        get_data = {
            "jsonrpc": "2.0",
            "method": "hostgroup.create",
            "params": {
                "name": group_name
            },
            "auth": token,
            "id": 22
        }

        post_header = {'Content-Type': 'application/json'}
        ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
        zabbix_ret = json.loads(ret.text)
        if 'error' in zabbix_ret:
            error = zabbix_ret.get('error')
            logger.info('error:' + error['message'] + ' ' + error['data'])
        elif 'result' in zabbix_ret:
            logger.info('Group' + group_name + '创建成功!')
        return zabbix_ret
    except Exception as e:
        resp_data = {
            "status": "Error",
            "message": "zabbix创建主机组失败",
            "detail": traceback.format_exc()
        }
        logger.exception(traceback.format_exc())
        return resp_data


# ---------zabbix创建用户-22--------------------
def zabbix_create_user(token, serverip, username, groupid, verify=None):
    url = serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "user.create",
        "params": {
            "alias": username,
            "usrgrps": [
                {
                    "usrgrpid": groupid  # 22:PMO Read ;21:Network Read
                }
            ],
        },
        "auth": token,
        "id": 22
    }

    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    if 'error' in zabbix_ret:
        error = zabbix_ret.get('error')
        logger.info('error:' + error['message'] + ' ' + error['data'])
    elif 'result' in zabbix_ret:
        logger.info('user' + username + '创建成功!')
    return zabbix_ret


# ---------zabbix创建空模板-id:23--------------------
def zabbix_create_template(token, serverip, group_id, template_name, verify=None):
    url = serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "template.create",
        "params": {
            "host": template_name,
            "groups": {
                "groupid": group_id
            },
        },
        "auth": token,
        "id": 23
    }

    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    template_info = zabbix_ret.get('result')
    return template_info


# ---------zabbix创建自动发现规则---25---------------
def zabbix_create_dis_rule(token, serverip, iprange, group_name, dchecks, verify=None):
    if dchecks == "9":
        dkey = "system.uname"
        ports = "10050"
    elif dchecks == "11":
        dkey = "sysName.0"
        ports = "161"
    else:
        logger.info("dchecks error:检查类型未识别")
    url = 'http://' + serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "drule.create",
        "params": {
            "name": group_name,
            "iprange": iprange,
            "dchecks": [
                {
                    "type": dchecks,
                    "key_": dkey,
                    "snmp_community": "{$SNMP_COMMUNITY}",
                    "ports": ports,
                    "uniq": "1",
                    "host_source": "3",
                    "name_source": "3"
                }
            ]
        },
        "auth": token,
        "id": 4
    }

    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    logger.info(ret)


# ---------zabbix创建维护期间---26---------------
def zabbix_create_maintenance(token, serverip, maintenance_name, active_since, active_till, host_type, hosts_ids,
                              timeperiods, verify=None):
    url = serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "maintenance.create",
        "params": {
            "name": maintenance_name,
            "active_since": active_since,  # 开始时间
            "active_till": active_till,  # 结束时间
            host_type: hosts_ids,  # groupids/hostids : hosts_ids(list)
            "timeperiods": timeperiods,
        },
        "auth": token,
        "id": 26
    }
    logger.info(get_data)
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    return zabbix_ret


# -------zabbix更新主机信息 id 31---------
def zabbix_update_host(token, serverip, hostid, update_type, update_value, verify=None):
    try:
        url = serverip + zabbix_api_path
        get_data = {
            "jsonrpc": "2.0",
            "method": "host.update",
            "params": {
                "hostid": hostid,
                update_type: update_value
            },
            "id": 31,
            "auth": token
        }
        post_header = {'Content-Type': 'application/json'}
        ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
        zabbix_ret = json.loads(ret.text)
        if 'error' in zabbix_ret:
            error = zabbix_ret.get('error')
            logger.info('error:' + error['message'] + ' ' + error['data'])
            resp_data = {
                "status": "Error",
                "message": "zabbix 更新主机信息失败",
                "detail": traceback.format_exc()
            }
        # elif 'result' in zabbix_ret:
        else:
            logger.info('Host' + hostid + '更新成功')
            resp_data = zabbix_ret
        return resp_data
    except Exception as e:
        resp_data = {
            "status": "Error",
            "message": "zabbix 更新主机信息失败",
            "detail": traceback.format_exc()
        }
        logger.exception(traceback.format_exc())
        return resp_data


# -------zabbix更新组信息 id 32---------
def zabbix_update_group(token, serverip, groupid, update_type, update_value, verify=None):
    url = serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "hostgroup.update",
        "params": {
            "groupid": groupid,
            update_type: update_value
        },
        "id": 32,
        "auth": token
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    ret_list = zabbix_ret.get('result')
    return ret_list


# ---------zabbix更新线路(用于线路监控)-33------------
def zabbix_update_line(token, serverip, hostid, hostip, hostname, name, groups, templateid, port_type, macros,
                       inventory, tags, status, verify=None):
    try:
        # 判断模板类型
        if isinstance(templateid, list):
            template_value = templateid
        else:
            logger.info(type(templateid))
            template_value = [
                {
                    "templateid": templateid
                }
            ]
        url = serverip + zabbix_api_path
        get_data = {
            "jsonrpc": "2.0",
            "method": "host.update",
            "params": {
                "hostid": hostid,
                "host": hostname,
                "name": name,
                "groups": groups,
                "templates": template_value,
                "macros": macros,
                "inventory_mode": 1,
                "inventory": inventory,
                "tags": tags,
                "status": status

            },
            "auth": token,
            "id": 33
        }
        post_header = {'Content-Type': 'application/json'}
        logger.info(json.dumps(get_data))
        ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
        zabbix_ret = json.loads(ret.text)
        if 'error' in zabbix_ret:
            error = zabbix_ret.get('error')
            logger.info('error:' + error['message'] + ' ' + error['data'])
            resp_data = {
                "status": "Error",
                "message": "zabbix更新线路(用于线路监控)失败",
                "detail": zabbix_ret.get('error'),
                "hostname": hostname
            }
            return resp_data
        elif 'result' in zabbix_ret:
            logger.info('host' + name + '更新成功')
        return zabbix_ret
    except Exception as e:
        resp_data = {
            "status": "Error",
            "message": "zabbix更新线路(用于线路监控)失败",
            "detail": traceback.format_exc(),
            "hostname": hostname
        }
        logger.exception(traceback.format_exc())
        return resp_data


# -------zabbix更新接口-id:34--------
def zabbix_uptade_hostinterface(token, serverip, interfaceid, ip, verify=None):
    try:
        url = serverip + zabbix_api_path
        get_data = {
            "jsonrpc": "2.0",
            "method": "hostinterface.update",
            "params": {
                "interfaceid": interfaceid,
                "ip": ip
            },
            "id": 34,
            "auth": token
        }
        post_header = {'Content-Type': 'application/json'}
        ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
        zabbix_ret = json.loads(ret.text)
        if 'error' in zabbix_ret:
            error = zabbix_ret.get('error')
            logger.info('error:' + error['message'] + ' ' + error['data'])
            resp_data = {
                "status": "Error",
                "message": "zabbix更新接口失败",
                "detail": error["message"] + error["data"]
            }
            return resp_data
        elif 'result' in zabbix_ret:
            logger.info('接口' + interfaceid + '已更新:' + str(zabbix_ret['result']))
            resp_data = {
                "status": "Update",
                "message": "zabbix更新接口成功",
            }
            return resp_data

        return zabbix_ret
    except Exception as e:
        resp_data = {
            "status": "Error",
            "message": "zabbix更新接口失败",
            "detail": traceback.format_exc()
        }
        logger.exception(traceback.format_exc())
        return resp_data


# -------zabbix更新用户组信息---------
def zabbix_update_usergroup(token, serverip, usrgrpid, rights, verify=None):
    '''
    :param token:
    :param serverip:
    :param groupid: 站点id
    :param rights: 用户组权限 'rights': [{'permission': '2', 'id': '477'}]
    :param permission:
        0 - access denied;
        2 - read-only access;
        3 - read-write access.
    :return:
    '''
    url = serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "usergroup.update",
        "params": {
            "usrgrpid": usrgrpid,
            "rights": rights
        },
        "auth": token,
        "id": 1
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    if zabbix_ret.get('result'):
        group_list = zabbix_ret.get('result')
    else:
        group_list = zabbix_ret
    return group_list


# -------zabbix删除host id：41--------
def zabbix_hosts_delete(token, serverip, hostids, verify=None):
    url = serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "host.delete",
        "params": hostids,
        "id": 41,
        "auth": token
    }

    post_header = {'Content-Type': 'application/json'}
    # print(str(json.dumps(get_data)))
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    if 'error' in zabbix_ret:
        error = zabbix_ret.get('error')
        logger.info('error:' + error['message'] + ' ' + error['data'])
    elif 'result' in zabbix_ret:
        logger.info('Host' + str(hostids) + '已删除:' + str(zabbix_ret['result']))

    return zabbix_ret


# -------zabbix主机组添加主机--id：51------
def zabbix_hostgroup_massadd(token, serverip, groupid, hostids, verify=None):
    url = serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "hostgroup.massadd",
        "params": {
            "groups": [
                {
                    "groupid": groupid,
                }
            ],
            "hosts": hostids,
        },
        "id": 51,
        "auth": token
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    if 'error' in zabbix_ret:
        error = zabbix_ret.get('error')
        logger.info('error:' + error['message'] + ' ' + error['data'])
    elif 'result' in zabbix_ret:
        logger.info('Host' + str(hostids) + '已添加到组:' + str(zabbix_ret['result']))

    return zabbix_ret


# -------zabbix主机组查找主机--id：54------
def zabbix_hostgroup_get(token, serverip, group_name, verify=None):
    url = serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "hostgroup.get",
        "params": {
            "output": "extend",
            "selectHosts": [
                'hostid',
            ],
            "filter": {
                "name": [
                    group_name,
                ]
            }
        },
        "id": 54,
        "auth": token
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    if 'error' in zabbix_ret:
        error = zabbix_ret.get('error')
        logger.info('error:' + error['message'] + ' ' + error['data'])
    elif 'result' in zabbix_ret:
        logger.info('Hostgroup' + str(group_name) + '发现hosts:' + str(zabbix_ret['result']))

    return zabbix_ret


# -------zabbix移除模板--id：52------
def zabbix_template_massremove(token, serverip, templateids, hostids, verify=None):
    url = serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "template.massremove",
        "params": {
            "templateids_link": templateids,
            "hosts": hostids,
        },
        "id": 52,
        "auth": token
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    if 'error' in zabbix_ret:
        error = zabbix_ret.get('error')
        logger.info('error:' + error['message'] + ' ' + error['data'])
    elif 'result' in zabbix_ret:
        logger.info('Host' + str(hostids) + '已添加到组:' + str(zabbix_ret['result']))

    return zabbix_ret

# 主机列表移除模板
def zabbix_host_massremove(token, serverip, templateids, hostids, verify=None):
    url = serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "host.massremove",
        "params": {
            # "templateids_link": templateids,
            # "hosts": hostids,
            "hostids": hostids,
            "templateids": templateids
        },
        "id": 52,
        "auth": token
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    if 'error' in zabbix_ret:
        error = zabbix_ret.get('error')
        logger.info('error:' + error['message'] + ' ' + error['data'])
    elif 'result' in zabbix_ret:
        logger.info('Host' + str(hostids) + '已添加到组:' + str(zabbix_ret['result']))

    return zabbix_ret


# -------zabbix移除主机组内主机--id：52------
def zabbix_hostgroup_massremove(token, serverip, groupids, hostids, verify=None):
    url = serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "hostgroup.massremove",
        "params": {
            "groupids": [
                groupids,  # str
            ],
            "hostids": hostids,  # list
        },
        "id": 52,
        "auth": token
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    if 'error' in zabbix_ret:
        error = zabbix_ret.get('error')
        logger.info('error:' + error['message'] + ' ' + error['data'])
    elif 'result' in zabbix_ret:
        logger.info('Host' + str(hostids) + '已从组中移除:' + str(zabbix_ret['result']))

    return zabbix_ret


# -------zabbix关联模板--id：53------
def zabbix_template_massadd(token, serverip, templateid, hostids, verify=None):
    url = serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "template.massadd",
        "params": {
            "templates": [
                {
                    "templateid": templateid,
                }
            ],
            "hosts": hostids,
        },
        "id": 53,
        "auth": token
    }
    logger.info(get_data)
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    if 'error' in zabbix_ret:
        error = zabbix_ret.get('error')
        logger.info('error:' + error['message'] + ' ' + error['data'])
    elif 'result' in zabbix_ret:
        logger.info('Host' + str(hostids) + '已关联到模板:' + str(zabbix_ret['result']))

    return zabbix_ret

# -------zabbix主机关联模板--id：53------
def zabbix_host_massadd(token, serverip, templateid, hostids, verify=None):
    url = serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "host.massadd",
        "params": {
            "templates": [
                {
                    "templateid": templateid,
                }
            ],
            "hosts": hostids,
        },
        "id": 53,
        "auth": token
    }
    logger.info(get_data)
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    if 'error' in zabbix_ret:
        error = zabbix_ret.get('error')
        logger.info('error:' + error['message'] + ' ' + error['data'])
    elif 'result' in zabbix_ret:
        logger.info('Host' + str(hostids) + '已关联到模板:' + str(zabbix_ret['result']))

    return zabbix_ret


# def get_zabbix_role(serverip, roleids, token):
#     url = serverip + zabbix_api_path
#     get_data = {
#         "jsonrpc": "2.0",
#         "method": "role.get",
#         "params": {
#             "output": "extend",
#             "selectRules": "extend",
#             "roleids": roleids,
#         },
#         "auth": token,
#         "id": 1
#     }
#     post_header = {'Content-Type': 'application/json'}
#     ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
#     zabbix_ret = json.loads(ret.text)
#     if 'error' in zabbix_ret:
#         error = zabbix_ret.get('error')
#         logger.info('error:' + error['message'] + ' ' + error['data'])
#     elif 'result' in zabbix_ret:
#         logger.info('Host' + str(hostids) + '已关联到模板:' + str(zabbix_ret['result']))
#
#     return zabbix_ret


# --------zabbix 创建用户 -------
def create_user(token, serverip, username, roleid, groupid):
    url = serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "user.create",
        "params": {
            "username": username,
            "roleid": roleid,
            "usrgrps": [
                {
                    "usrgrpid": groupid
                }
            ],
            # "medias": [
            #     {
            #         "mediatypeid": "1",
            #         "sendto": [
            #             "support@company.com"
            #         ],
            #         "active": 0,
            #         "severity": 63,
            #         "period": "1-7,00:00-24:00"
            #     }
            # ]
        },
        "auth": token,
        "id": 1
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    return zabbix_ret


# ------ 获取用户信息 -------
def zabbix_get_user(token, serverip, filter_key, filter_value):
    url = serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "user.get",
        "params": {
            "selectUsrgrps": True,
            "filter": {
                filter_key: filter_value,
            },
        },
        "auth": token,
        "id": 1
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    return zabbix_ret


def zabbix_get_all_user(token, serverip, filter_key, filter_value):
    url = serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "user.get",
        "params": {
            "selectUsrgrps": True,
            "filter": {
                filter_key: filter_value,
            },
        },
        "auth": token,
        "id": 1
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    return zabbix_ret


# ------ 修改用户信息 -------
def zabbix_update_user(token, serverip, user_id, filter_key, filter_value):
    url = serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "user.update",
        "params": {
            "userid": user_id,
            filter_key: filter_value,
        },
        "auth": token,
        "id": 1
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    return zabbix_ret


# ------ 获取用户所在组信息 -------
def zabbix_get_user_group(token, serverip, filter_key, filter_value):
    url = serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "usergroup.get",
        "params": {
            filter_key: filter_value,
        },
        "auth": token,
        "id": 1
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    return zabbix_ret


# 获取zabbix的service服务
def zabbix_get_service(token, serverip, serviceids=None, parentids=None):
    url = serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "service.get",
        "params": {
            "output": "extend",
        },
        "auth": token,
        "id": 1
    }
    if parentids:
        get_data["params"]["parentids"] = parentids
    if serviceids:
        get_data["params"]["serviceids"] = serviceids

    # if parentids:
    #     params = {
    #         "output": "extend",
    #         "parentids": parentids,
    #         # "selectDependencies": "extend"
    #     },
    # else:
    #     params = {
    #         "output": "extend",
    #     },
    # get_data = {
    #     "jsonrpc": "2.0",
    #     "method": "service.get",
    #     "params": params,
    #     "auth": token,
    #     "id": 1
    # }

    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    return zabbix_ret


def zabbix_create_service(token, serverip, name, tags, description=None, parents=None, algorithm=1,
                          propagation_rule=None):
    url = serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "service.create",
        "params": {
            "name": name,
            "algorithm": algorithm,
            "sortorder": 1,
            "tags": tags,
        },
        "auth": token,
        "id": 1
    }
    if description:
        get_data["params"]["description"] = description
    if parents:
        get_data["params"]["parents"] = parents
        # get_data["params"]["parents"] = parents
    if propagation_rule:
        get_data["params"]["propagation_rule"] = propagation_rule
        get_data["params"]["propagation_value"] = 1

    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    return zabbix_ret


def zabbix_update_service(token, serverip, serviceid, tags=None, name=None, description=None, parents=None):
    url = serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "service.update",
        "params": {
            "serviceid": serviceid,
        },
        "auth": token,
        "id": 1
    }
    if description:
        get_data["params"]["description"] = description
    if parents:
        get_data["params"]["parents"] = parents
    if tags:
        get_data["params"]["tags"] = tags
    if name:
        get_data["params"]["name"] = name
        # get_data["params"]["parents"] = parents

    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    return zabbix_ret

# token = '384eb4377e12b40dc79c6191358743b1'
# serverip = "http://10.26.5.40/zabbix"
# name = "test_1"
# tags = [
#     {"tag": "site_id", "value": '1'}
# ]
# parents = [{"serviceid": 522}]
# description = "site_id=10"
# status_rules = [{"type": 0}, {"limit_value": 100}, {"new_status": 5}, {"limit_status": 5}]
# status = 5
# serviceid = 200
# zabbix_get = zabbix_get_service(token, serverip, serviceids=200)
# get_childids_service = zabbix_get_service(token, serverip, parentids=272)
# zabbix_updated = zabbix_update_service(token, serverip, serviceid, parents=[{"serviceid": 10}])
# zabbix_created_service = zabbix_create_service(token, serverip, name, tags, description=description,parents=parents)
# print(zabbix_created_service)
